package com.mf.controller.queue;

import com.mf.result.Result;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;

/**
 * @Author: lmf
 * @Create: 2025/5/22 22:55
 * @module 等待队列使用
 */
@RestController
@RequestMapping("/synchronousQueue")
public class SynchronousQueueUse {
    @Operation(summary = "不等待会拿不到消息")
    @GetMapping("test")
    public Result<String> test() throws InterruptedException {
        final SynchronousQueue<String> queue = new SynchronousQueue<>();

        String msg = "消息";

        new Thread(() -> {
            // 存入数据
            final boolean offer = queue.offer(msg);
            System.out.println(offer);
        }).start();

        Thread.sleep(100);

        new Thread(() -> {
            // 获取数据
            final String take = queue.poll();
            System.out.println(take + "拿到的任务");
        }).start();
        return Result.success();
    }

    @Operation(summary = "等待会拿到消息")
    @GetMapping("test2")
    public Result<String> test2() throws InterruptedException {
        final SynchronousQueue<String> queue = new SynchronousQueue<>();

        String msg = "我是消息";

        new Thread(() -> {
            // 存入数据(如果没有消费者等待1分钟)
            final boolean offer;
            try {
                offer = queue.offer(msg, 1, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println(offer);
        }).start();

        Thread.sleep(100);

        new Thread(() -> {
            // 获取数据
            final String take = queue.poll();
            System.out.println(take + "--拿到的任务");
        }).start();
        return Result.success();
    }


}
